<template>
  <div id="Users">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card >
      <!-- 搜索与添加区域 -->    
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" :clearable="true" @clear="getUserList" >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" :border="true" :stripe="true">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" >
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" >
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <!-- 删除 -->
            <el-button @click="removeUserById(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button @click="setRole(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>           
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 对话框关闭触发close -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="30%" @close="addDialogClosed" 
      >
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!-- 内容主体区 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed">
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getHttpUserList,putHttpUserState, postHttpAddUser, getHttpGetUser, putHttpUserInfo, deleteHttpDeleteUserById, putHttpUpdateUserRole } from 'network/users'
import { getHttpRolesList } from 'network/roles'
import { usernameVf, passwordVf, emailVf, mobileVf } from 'common/js/validator'
export default {
  name: "Users",
  data() {
    return {
      //获取用户列表的查询参赛对象
      queryInfo: {
        query: '',
        //当前的页码
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 2
      },
      userlist: [],
      total: 0,
      //添加用户对话框是否弹出
      addDialogVisible: false,
      //修改用户对话框是否弹出
      editDialogVisible: false,
      // 添加用户表单
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //表单验证对象
      addFormRules: {
        username: usernameVf,
        password:passwordVf,
        email: emailVf,
        mobile: mobileVf
      },
      // 用户修改验证对象
      editFormRules : {
        email: emailVf,
        mobile: mobileVf
      },
      //用户修改信息对象
      editForm: {

      },
      //分配角色对话框显示隐藏
      setRoleDialogVisible: false,
      //点击分配角色按钮事件时保存的单个用户信息
      userInfo: {},
      //所有角色的数据列表
      rolesList: [],
      //分配角色选择的值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    getUserList() {
      getHttpUserList(this.queryInfo).then(res => {
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        this.userlist = res.data.users 
        this.total = res.data.total
      }).catch(err => {
        this.$message.error(err)
      })
    },
    //监听每页显示多少条事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //用户状态改变事件 监听switch开关状态的改变
    userStateChanged(userinfo) {
      console.log(userinfo)
      putHttpUserState(userinfo).then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          userinfo.ms_state = !userinfo.ms_state
          return
        }
        else{
          this.$message.success(res.meta.msg)
        }
        console.log(res)
      }).catch(err => {
        this.$message.error(err)
      })
    },
    //监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //点击确定按钮  添加用户
    addUser() {
      //addDialogVisible = false
      //表单验证
      this.$refs.addFormRef.validate(valid => {
        if(!valid) {
          return
        }
        else {
          postHttpAddUser(this.addForm).then(res => {
            if( res.meta.status !== 201) {
              this.$message.error(res.meta.msg)
              return
            }
            else
            {
              this.$message.success(res.meta.msg)
              this.addDialogVisible = false
              this.getUserList()
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      })
    },
    //修改用户事件
    showEditDialog(id) {
      //查询用户信息
      getHttpGetUser(id).then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        else {
          this.editForm = res.data
        }
      }).catch(err => {
        this.$message.error(err)
      })    
      this.editDialogVisible = true
    },
    //修改用户对话框关闭事件
    editDialogClosed() {
      //console.log('对话框关闭')
      this.$refs.editFormRef.resetFields()
    },
    //修改用户信息提交事件
    editUserInfo() {
      //检查表单验证
      this.$refs.editFormRef.validate(valid => {
        if(!valid) {
          this.$message.error('表单验证失败')
          return
        }
        else {
          putHttpUserInfo(this.editForm).then(res => {
            if( res.meta.status !== 200) {
              this.$message.error(res.meta.msg)
              return
            }
            else {
              this.$message.success(res.meta.msg)
              this.editDialogVisible = false
              this.getUserList()
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      })
    },
    //用户删除事件
    removeUserById(id) {
      //弹窗询问用户是否删除数据
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteHttpDeleteUserById(id).then(res => {
            if( res.meta.status !== 200) {
              this.$message.error(res.meta.msg)
              return
            }
            else {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getUserList()
            }
          }).catch(err => {
            this.$message.error(err)
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })          
        })
    },
    //分配角色对话框点击事件
    setRole(userInfo) {
      this.userInfo = userInfo
      //获取所有角色列表
      getHttpRolesList().then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        else {
          this.rolesList = res.data
        }
      }).catch(err => {
        this.$message.error(err)
      })
      this.setRoleDialogVisible = true
    },
    //分配角色点击确定按钮事件
    saveRoleInfo() {
      //如果角色ID没有值
      if(!this.selectedRoleId){
        this.$message.error('没有选择角色')
        return
      }
      else {
        putHttpUpdateUserRole(this.userInfo.id,this.selectedRoleId).then(res => {
          if( res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            return
          }
          else {
            this.$message.success(res.meta.msg)
            this.getUserList()
            this.setRoleDialogVisible = false
          }
        }).catch(err => {
          this.$message.error(err)
        })
      }
    },
    //分配角色弹框关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang='less' scoped>
</style>
